import React, { PureComponent } from 'react'

export default class App extends PureComponent {
  constructor(props) {
    super(props)

    this.state ={
      friends: [
        {name: 'jack', age: 20},
        {name: 'Tom', age: 19},
        {name: 'Jerry', age: 27}
      ]
    }
  }

  render() {
    return (
      <div>
        <h2>Friends List</h2>
        <ul>
          {
            this.state.friends.map((item, index) => {
              return (
                <li key={item.name}>
                  Name: {item.name} 
                  Age: {item.age} 
                  <button onClick={ e => this.incrementAge(index) }>Age +1</button>
                </li>
              )
            })
          }
        </ul>
        <button onClick={ e => this.insertData() }>Add New Data</button>
      </div>
    )
  }

  // shouldComponentUpdate(newProps, newState) {
  //   if (newState.friends !== this.state.friends) {
  //     return true
  //   }
  //   return false
  // }

  incrementAge(index) {
    const newFriends = [...this.state.friends]
    newFriends[index].age += 1
    this.setState({
      friends: newFriends
    })
  }

  insertData() {
    const newData = {name: 'jack' + Math.random().toFixed(3) * 1000, age: 20}
    this.setState({
      friends: [...this.state.friends, newData]
    })
  }
}
